import 'dart:convert';
import 'dart:io';

import 'package:xws/helpers/as_t.dart';

// const iosMsg = {
//   "extras": {
//     "extras": "{\"conversationId\":\"61d2e8daaaf4850b23e9d3c0\",\"messageId\":\"62335b8ebbb485306d2a4abf\",\"content\":\"4423\",\"messageType\":\"TEXT\"}",
//     "_j_data_": "{\"data_msgtype\":1,\"push_type\":8,\"is_vip\":0}"
//   },
//   "aps": {"alert": "4423", "badge": 1, "sound": ""},
//   "_j_data_": "{\"data_msgtype\":1,\"push_type\":8,\"is_vip\":0}",
//   "_j_uid": 61222749042,
//   "_j_msgid": 18100020347422572,
//   "_j_business": 1
// };

/// 极光推送消息对象
class JPushObj {
  JPushObj({
    required this.notifyId,
    required this.msgId,
    required this.alert,
    required this.extras,
    required this.title,
    required this.androidExtra,
  });

  factory JPushObj.fromJson(Map<String, dynamic> jsonRes) {
    String notify = jsonRes['extras']['cn.jpush.android.EXTRA'].toString();
    notify = asT<Map<String, dynamic>>(json.decode(notify))['extras'].toString();

    int notifyId = 0;
    String msgId = 'ios msgId';

    if (Platform.isAndroid) {
      notifyId = asT<int>(jsonRes['extras']['cn.jpush.android.NOTIFICATION_ID']);
      msgId = asT<String>(jsonRes['extras']['cn.jpush.android.MSG_ID']);
    } else {
      notifyId = asT<int>(jsonRes['_j_msgid']);
      msgId = asT<String>(jsonRes['_j_msgid']);
    }

    final Map<String, dynamic> notifyData = asT<Map<String, dynamic>>(json.decode(notify));

    return JPushObj(
      notifyId: notifyId,
      msgId: msgId,
      alert: asT<String>(jsonRes['alert']),
      title: asT<String>(jsonRes['title']),
      extras: asT<Map<String, dynamic>>(jsonRes['extras']['extras']),
      androidExtra: notifyData,
    );
  }

  late int notifyId;
  late String msgId;
  late String alert;
  late Map<String, dynamic> extras;
  late String title;
  late Map<String, dynamic> androidExtra;

  Map<String, dynamic> get getExtras => Platform.isAndroid ? androidExtra : extras;
}
